package com.syt.cellphone.information.utils

import com.google.gson.JsonSyntaxException
import kotlinx.coroutines.TimeoutCancellationException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

/**
 *  @author: syt
 *  创建时间: 2020/9/3 9:42
 *  @功能   异常拓展
 *  @version v1.0
 */

/**
 * 异常状态码
 */
val Throwable.msg: Int
    get() {
        val errorCode = when (this) {
//            is HttpStatusCodeException -> this.statusCode
//            is ParseException -> this.errorCode
            else -> "-1"
        }
        return try {
            errorCode.toInt()
        } catch (e: Exception) {
            -1
        }
    }

/**
 * 异常信息
 */
fun Throwable.msg(): String =
     if (this is UnknownHostException) { //网络异常
        "当前无网络，请检查你的网络设置"
    } else if (
        this is SocketTimeoutException  //okhttp全局设置超时
        || this is TimeoutException     //rxjava中的timeout方法超时
        || this is TimeoutCancellationException  //协程超时
    ) {
        "连接超时,请稍后再试"
    } else if (this is ConnectException) {
        "网络不给力，请稍候重试！"
    }
//     else if (this is HttpStatusCodeException) {               //请求失败异常
//        "Http状态码异常"
//    }
     else if (this is JsonSyntaxException) {  //请求成功，但Json语法异常,导致解析失败
        "数据解析失败,请检查数据是否正确"
    }
//     else if (this is ParseException) {       // ParseException异常表明请求成功，但是数据不正确
//        this.message ?: errorCode   //msg为空，显示code
//    }
     else {
        "请求失败，请稍后再试"
    }
